package org.byqh.dqeai.config;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.byqh.dqeai.common.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler({ServletException.class})
    @ResponseBody
    public Json<Object> exception(ServletException ex, HttpServletRequest request, HttpServletResponse response) {
        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append(request.getRequestURL()); // 获取完整 URL
        if (request.getQueryString() != null) {
            requestUrl.append("?").append(request.getQueryString()); // 添加查询参数
        }

        return handleException(String.format("REST 请求错误: %s : ", requestUrl), ex);
    }

    //其他错误
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Json<Object> exception(Exception ex) {
        return handleException("服务器内部错误: ", ex);
    }

    private Json<Object> handleException(String prefix, Exception ex) {
        String message = prefix + ex.getMessage();

        logger.error(message, ex);

        return Json.error(
                message,
                null,
                HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
}